{% extends 'user/product_base.html' %}

{% block extendcss %}
    <style>
        .to-top{
            position: fixed;
            right: 20px;
            z-index: 10;
            bottom: 82px;
            cursor: pointer;
            width: 42px;
            height: 42px;
        }
        .comment-section {
            margin-top: 20px;
            border-top: 1px solid #ccc;
            padding-top: 20px;
        }
        .comment-list {
            list-style-type: none;
            padding: 0;
        }
        .comment-item {
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .comment-content {
            margin-top: 5px;
            font-size: 14px;
        }
    </style>
{% endblock %}
{% block content %}
<!-- Main content 主要内容---->
{#鲜花专区#}
    <section class="pt-0 pl-lg-6" data-aos="zoom-in">
        <div class="page-body pb-5">
            <div class="container-xl ">
                <!-- flower 标题 -->
                <div class="row mb-2 text-left">
                        <div class="col col-lg-4 ">
                            <h3 class="mt-4" style="font-family: Helvetica Neue,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif; font-size: 40px; font-weight: 400">{{ flowers.name }}</h3>
                            <div class="mt-2">
                                <p class="lead lh-180"><span>{{ flowers.name| truncate(4) }}</span>{{ flowers.published_date }}----来源：哈哈哈</p>
                            </div>
                            <div class="mt-4 d-flex justify-content-between">
                                <form action="{{ url_for('cart.add_to_cart', flower_id=flowers.id) }}" method="POST" style="display:inline;">
                                    <button type="submit" class="btn btn-sm btn-primary">添加到购物车</button>
                                </form>
                            </div>
                        </div>
                </div>
                <!-- flower  -->
                <div class="row">
                    <!-- flower 内容 -->
                    <div class="col col-lg-8">
                        <div class="card flex-column card-lg">
                            <div class="card-body markdown">
                                <h4>简介</h4>
                                <p>{{ flowers.description }}</p>
                            </div>
                        </div>
                    </div>
                    <!-- flower 图片 -->
                    <div class="col col-lg-3">
                        <div class="card card-lg py-3 flex-column align-items-center justify-content-center">
                            <h4 class="">图片</h4>
                            <img height="200px" width="200px" src="{{ flowers.flowerImg }}" alt="">
                        </div>
                        <div class="card card-lg py-3 justify-content-center">
                            <img height="200px" width="200px" src="{{ flowers.flowerImg }}" alt="">
                        </div>
                    </div>
                </div>

                <!-- 评论表单 -->
                <div class="comment-section">
                    <h4>用户评论</h4>
                    <form id="commentForm">
                        <textarea name="content" rows="3" required placeholder="写下你的评论..." class="form-control"></textarea>
                        <button type="submit" class="btn btn-primary mt-2">提交评论</button>
                    </form>

                    <h5>全部评论 (<span id="commentCount">{{ flowers.comments|length }}</span>)</h5>
                    <ul class="comment-list" id="commentList">
                        {% for comment in flowers.comments %}
                            <li class="comment-item" id="comment-{{ comment.id }}">
                                <div class="comment-header">
                                    <strong>{{ comment.user.username }}{% if comment.user_id == session['user_id'] %}（我）{% endif %}</strong>
                                    <small class="text-muted">{{ comment.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</small>
                                    {% if comment.user_id == session['user_id'] %}
                                        <button class="btn btn-link btn-sm text-danger delete-comment" data-id="{{ comment.id }}">删除</button>
                                    {% endif %}
                                </div>
                                <p class="comment-content">{{ comment.content }}</p>
                            </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
    </section>
    <!-- {#    置顶#} -->
     <div id="to_top" >
         <img class="to-top" src="{{ url_for('static', filename='front/images/Totop.png') }}" alt="">
     </div>
{% if request.args.get('login_required') and not session.get('user_id') %}
<script>
    if (confirm('请先登录才能评论！')) {
        window.location.href = "{{ url_for('login.login', next=request.url) }}";
    }
</script>
{% endif %}

{% if request.args.get('deleted') %}
<script>
    alert('评论已删除！');
</script>
{% endif %}

{% if request.args.get('delete_failed') %}
<script>
    alert('无法删除评论！');
</script>
{% endif %}

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 处理评论提交
    document.getElementById('commentForm').addEventListener('submit', function(event) {
        event.preventDefault();
        console.log('提交评论表单');
        const formData = new FormData(this);
        fetch("{{ url_for('flower.add_flower_comment', flower_id=flowers.id) }}", {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            console.log('提交评论响应:', data);
            if (data.success) {
                const commentList = document.getElementById('commentList');
                const newComment = document.createElement('li');
                newComment.className = 'comment-item';
                newComment.id = `comment-${data.comment_id}`;
                newComment.innerHTML = `
                    <div class="comment-header">
                        <strong>${data.username}（我）</strong>
                        <small class="text-muted">${data.created_at}</small>
                        <button class="btn btn-link btn-sm text-danger delete-comment" data-id="${data.comment_id}">删除</button>
                    </div>
                    <p class="comment-content">${data.content}</p>
                `;
                commentList.appendChild(newComment);
                document.getElementById('commentCount').textContent = parseInt(document.getElementById('commentCount').textContent) + 1;
                this.reset();

                // 显示提交成功提示信息
                const alertBox = document.createElement('div');
                alertBox.className = 'alert alert-success';
                alertBox.textContent = '评论提交成功！';
                alertBox.style.position = 'fixed';
                alertBox.style.top = '50%';
                alertBox.style.left = '50%';
                alertBox.style.transform = 'translate(-50%, -50%)';
                alertBox.style.zIndex = '1000';
                document.body.appendChild(alertBox);
                console.log('提交成功提示信息已显示');

                // 2秒后自动消失
                setTimeout(() => {
                    alertBox.remove();
                    console.log('提交成功提示信息已移除');
                }, 2000);
            } else {
                alert(data.message);
            }
        });
    });

    // 处理评论删除
    document.getElementById('commentList').addEventListener('click', function(event) {
        if (event.target.classList.contains('delete-comment')) {
            const commentId = event.target.getAttribute('data-id');
            console.log('删除评论ID:', commentId);
            fetch(`{{ url_for('flower.delete_flower_comment', flower_id=flowers.id, comment_id=0) }}`.replace('0', commentId), {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                console.log('删除评论响应:', data);
                if (data.success) {
                    const commentItem = document.getElementById(`comment-${commentId}`);
                    console.log('删除评论响应commentItem:', commentItem);
                    if (commentItem) {
                        commentItem.remove();
                        document.getElementById('commentCount').textContent = parseInt(document.getElementById('commentCount').textContent) - 1;

                        // 显示删除成功提示信息
                        const alertBox = document.createElement('div');
                        alertBox.className = 'alert alert-danger';
                        alertBox.textContent = '评论删除成功！';
                        alertBox.style.position = 'fixed';
                        alertBox.style.top = '50%';
                        alertBox.style.left = '50%';
                        alertBox.style.transform = 'translate(-50%, -50%)';
                        alertBox.style.zIndex = '1000';
                        document.body.appendChild(alertBox);
                        console.log('删除成功提示信息已显示');

                        // 2秒后自动消失
                        setTimeout(() => {
                            alertBox.remove();
                            console.log('删除成功提示信息已移除');
                        }, 2000);
                    }
                } else {
                    alert(data.message);
                }
            });
        }
    });
});
</script>
{% endblock %}
{% block js %}
<script>
        document.getElementById('to_top').addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
</script>
{% endblock %}